package cn.iocoder.yudao.module.erp.controller.admin.dp.dpyw;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.erp.controller.admin.dispatchvehicle.vo.DispatchVehicleRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.dispatchvehicle.vo.DispatchVehicleSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.dp.dpyw.vo.DpYwPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.dp.dpyw.vo.DpYwRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.dp.dpyw.vo.DpYwSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dispatchvehicle.DispatchVehicleDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dpitem.DpItemYwDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dplist.DpEastListYwDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dplist.DpWestListYwDO;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.module.erp.dal.dataobject.dp.DpYwDO;
import cn.iocoder.yudao.module.erp.service.dp.DpYwService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - ERP义乌制单")
@RestController
@RequestMapping("/erp/dp-yw")
@Validated
public class DpYwController {

    @Resource
    private DpYwService dpYwService;

    @PostMapping("/create")
    @Operation(summary = "创建ERP义乌制单")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:create')")
    public CommonResult<String> createDpYw(@Valid @RequestBody DpYwSaveReqVO createReqVO) {
        return success(dpYwService.createDpYw(createReqVO));
    }

//    @PostMapping("/configCar")
//    @Operation(summary = "ERP义乌运单配车")
//    @PreAuthorize("@ss.hasPermission('erp:dispatch-vehicle-yw:configcar')")
//    public CommonResult<Boolean> configCar(@RequestParam("dispatchNumber") String dispatchNumber,
//                                           @Valid @RequestBody List<DispatchorderitemYwSaveReqVO> createReqVO) {
//        return success(dpYwService.configCar(dispatchNumber,createReqVO));
//    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP义乌制单")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:update')")
    public CommonResult<Boolean> updateDpYw(@Valid @RequestBody DpYwSaveReqVO updateReqVO) {
        dpYwService.updateDpYw(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除ERP义乌制单")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:delete')")
    public CommonResult<Boolean> deleteDpYw(@RequestParam("id") String id) {
        dpYwService.deleteDpYw(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP义乌制单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:query')")
    public CommonResult<DpYwRespVO> getDpYw(@RequestParam("id") String id) {
        DpYwDO dpYw = dpYwService.getDpYw(id);
        return success(BeanUtils.toBean(dpYw, DpYwRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP义乌制单分页")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:query')")
    public CommonResult<PageResult<DpYwRespVO>> getDpYwPage(@Valid DpYwPageReqVO pageReqVO) {
        PageResult<DpYwDO> pageResult = dpYwService.getDpYwPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DpYwRespVO.class));
    }


    @GetMapping("/dpYwOuterList")
    @Operation(summary = "获得ERP义乌制单出库列表")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:outer')")
    public CommonResult<PageResult<DpYwRespVO>> dpYwOuterList(@Valid DpYwPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<DpYwDO> dpYwOuterList = dpYwService.dpYwOuterList(pageReqVO);
        return success(BeanUtils.toBean(dpYwOuterList, DpYwRespVO.class));
    }

    @GetMapping("/dpYwVehicleList")
    @Operation(summary = "获得ERP义乌配车列表")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:outer')")
    public CommonResult<PageResult<DpYwRespVO>> dpYwVehicleList(@Valid DpYwPageReqVO pageReqVO) {
        PageResult<DpYwDO> dpYwOuterList = dpYwService.dpYwOuterList(pageReqVO);
        return success(BeanUtils.toBean(dpYwOuterList, DpYwRespVO.class));
    }


    @GetMapping("/dpYwEnterList")
    @Operation(summary = "获得ERP义乌制单入库列表")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:enter')")
    public CommonResult<List<DispatchVehicleRespVO>> dpYwEnterList(@RequestParam(value = "dispatchNumber",required = false) String dispatchNumber,
                                                                   @RequestParam(value = "line",required = false) Integer line,
                                                                   @RequestParam(value = "dest",required = false) Integer dest,
                                                                   @RequestParam(value = "dpId",required = false) String dpId) {
        List<DispatchVehicleDO> dpYwEnterList = dpYwService.dpYwEnterList(dispatchNumber,line,1, dest,dpId);
        return success(BeanUtils.toBean(dpYwEnterList, DispatchVehicleRespVO.class));
    }

//    @GetMapping("/unOutBound/page")
//    @Operation(summary = "获得ERP义乌制单审核未出库列表分页")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:query')")
//    public CommonResult<PageResult<DpYwRespVO>> getUnOutBoundDpYwPage(@Valid DpYwPageReqVO pageReqVO) {
//        PageResult<DpYwDO> pageResult = dpYwService.getUnOutBoundDpYwPage(pageReqVO);
//        return success(BeanUtils.toBean(pageResult, DpYwRespVO.class));
//    }

    @PostMapping("/dpYwOutStroe")
    @Operation(summary = "ERP义乌制单配车出库")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:outer')")
    public CommonResult<Boolean> dpYwOutStroe(@Valid @RequestBody DispatchVehicleSaveReqVO createReqVO) {
        dpYwService.dpYwOutStroe(createReqVO);
        return success(true);
    }

    @PostMapping("/enterStroeDpYw")
    @Operation(summary = "ERP义乌运单入库")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:enter')")
    public CommonResult<Boolean> enterStroeDpYw(@Valid @RequestBody List<DispatchVehicleSaveReqVO> createReqVO) {
        dpYwService.enterStroeDpYw(createReqVO);
        return success(true);
    }

    @GetMapping("/dpYwAndItem/page")
    @Operation(summary = "获得ERP义乌制单和详情分页")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:query')")
    public CommonResult<PageResult<DpYwRespVO>> getDpYwAndItemPage(@Valid DpYwPageReqVO pageReqVO) {
        PageResult<DpYwDO> pageResult = dpYwService.getDpYwAndItemPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DpYwRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP义乌制单 Excel")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDpYwExcel(@Valid DpYwPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DpYwDO> list = dpYwService.getDpYwPage(pageReqVO).getList();
        // 对数据进行字段处理
        List<DpYwRespVO> processedList = list.stream().map(dpYwDO -> {
            DpYwRespVO respVO = BeanUtils.toBean(dpYwDO, DpYwRespVO.class);
            // 转换核销字段
            if (dpYwDO.getWriteOff() != null){
                respVO.setWriteOffFormatted(dpYwDO.getWriteOff() == 1 ? "是" : "否");
            }
            // 转换线路字段
            if (dpYwDO.getLine() != null) {
                respVO.setLineFormatted(dpYwDO.getLine() == 1 ? "东线" : "西线");
            }
            return respVO;
        }).collect(Collectors.toList());
        processedList.add(new DpYwRespVO());
        processedList.add(new DpYwRespVO());

        // 创建提示信息行，并将其添加到列表末尾
        DpYwRespVO footerRow = new DpYwRespVO();
        footerRow.setId("注意：" +
                "一：提货时双方当面交接清楚，如货物提走后发现损坏少货现象本公司不负责。\n" +
                "二：预期不提货者，产生一切费用及后果由客户自己承担。\n" +
                "三：易碎的货物在承运过程中发现破碎、丢失时，只赔偿丢失的货物，不赔偿破损的货物。\n" +
                "义乌库房地址:浙江省义乌市苏溪高君路7号(浙江博尼锦纶服份有限公司西)大门进去直走100米311库房 电话/Tel:15600000311(微信同号)\n" +
                "广州库房地址:广东省佛山市南海区里水镇河塱沙里水东部工业园10号南海毛中厂二期(东侧大院311库房) 电话/Te1:18500000311(微信同号)\n" +
                "新疆库房地址:新疆维吾尔自治区乌鲁木齐市沙依巴克区青葱路1048号附1号楼311库 电话/Te1:18199990311(微信同号)");
        // 将提示信息添加到列表末尾
        processedList.add(footerRow);
        // 导出 Excel
        ExcelUtils.write(response, "ERP义乌制单.xls", "数据", DpYwRespVO.class, processedList);
    }

    @PutMapping("/examine")
    @Operation(summary = "ERP物流义乌制单审核")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:examine')")
    public CommonResult<Boolean> examineDpYw(@Valid @RequestBody DpYwDO dpYwDO){
        dpYwService.examineDpYw(dpYwDO);
        return success(true);
    }

    @GetMapping("/export-list")
    @Operation(summary = "导出ERP义乌制单东西线清单")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:exportlist')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDpYwExcelList(@Valid DpYwDO dpYwDO, HttpServletResponse response) throws IOException {
        //获取线路类型
        Integer  line = dpYwDO.getLine();
        List<DpEastListYwDO> dpEastList = dpYwService.getDpEastListYwListByNo(dpYwDO.getNo());
        List<DpWestListYwDO> dpWestList = dpYwService.getDpWestListYwListByNo(dpYwDO.getNo());

        if (line.equals(1)){
            // 导出 Excel东线清单
            ExcelUtils.write(response, "ERP义乌制单东线清单.xls", "清单", DpEastListYwDO.class,
                    BeanUtils.toBean(dpEastList, DpEastListYwDO.class));
        }
        if (line.equals(2)){
            // 导出 Excel西线清单
            ExcelUtils.write(response, "ERP义乌制单西线清单.xls", "清单", DpWestListYwDO.class,
                    BeanUtils.toBean(dpWestList, DpWestListYwDO.class));
        }
    }


    // ==================== 子表（ERP义乌制单货号详情） ====================

    @GetMapping("/dp-item-yw/list-by-no")
    @Operation(summary = "获得ERP义乌制单货号详情列表")
    @Parameter(name = "no", description = "入库编号")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:detail')")
    public CommonResult<List<DpItemYwDO>> getDpItemYwListByNo(@RequestParam("no") String no) {
        return success(dpYwService.getDpItemYwListByNo(no));
    }

    // ==================== 子表（义乌东线清单） ====================

    @GetMapping("/dp-east-list-yw/list-by-no")
    @Operation(summary = "获得义乌东线清单列表")
    @Parameter(name = "no", description = "运单号")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:detail')")
    public CommonResult<List<DpEastListYwDO>> getDpEastListYwListByNo(@RequestParam("no") String no) {
        return success(dpYwService.getDpEastListYwListByNo(no));
    }

    // ==================== 子表（义乌西线清单） ====================

    @GetMapping("/dp-west-list-yw/list-by-no")
    @Operation(summary = "获得义乌西线清单列表")
    @Parameter(name = "no", description = "运单号")
//    @PreAuthorize("@ss.hasPermission('erp:dp-yw:detail')")
    public CommonResult<List<DpWestListYwDO>> getDpWestListYwListByNo(@RequestParam("no") String no) {
        return success(dpYwService.getDpWestListYwListByNo(no));
    }


}